<template>
  <basic-dialog v-model="visible" :title="title">
    <el-container>
      <div id="entityRelation" style="width: 1380px; height: 600px"></div>
    </el-container>
  </basic-dialog>
</template>

<script setup>
import gojs from 'gojs'
import { apiGetEr } from '../../../../apis/objectModel/businessType'
import { watch } from 'vue'

const visible = defineModel()
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({}),
  },
})

const title = ref('')
const myDiagram = ref({})
const tabRelView = ref([])
const tabViewList = ref([])

const getErAndRender = async () => {
  const obj = await apiGetEr(props.curRow.id)
  showNodes(obj)
}

const showNodes = (obj) => {
  wrapperNode(obj)
  const $ = gojs.GraphObject.make
  myDiagram.value = $(gojs.Diagram, 'entityRelation', {
    initialContentAlignment: gojs.Spot.Center,
    allowDelete: false,
    allowCopy: false,
    layout: $(gojs.ForceDirectedLayout),
    'undoManager.isEnabled': true,
  })
  myDiagram.value.nodeTemplate = $(
    gojs.Node,
    'Auto',
    {
      selectionAdorned: true,
      resizable: true,
      layoutConditions: gojs.Part.LayoutStandard & ~gojs.Part.LayoutNodeSized,
      fromSpot: gojs.Spot.AllSides,
      toSpot: gojs.Spot.AllSides,
      isShadowed: true,
      shadowColor: '#CCAA',
    },
    new gojs.Binding('location', 'location').makeTwoWay(),
    new gojs.Binding('desiredSize', 'visible', function () {
      return new gojs.Size(NaN, NaN)
    }).ofObject('LIST'),
    $(
      gojs.Shape,
      'Rectangle',
      new gojs.Binding('fill', 'isHighlighted', function (h) {
        return h ? '#F44336' : '#A7E7FC'
      }).ofObject()
    ),
    $(
      gojs.Panel,
      'Table',
      { margin: 15, stretch: gojs.GraphObject.Fill },
      $(gojs.RowColumnDefinition, {
        row: 0,
        sizing: gojs.RowColumnDefinition.None,
      }),
      // the table header
      $(
        gojs.TextBlock,
        {
          row: 0,
          alignment: gojs.Spot.Center,
          margin: new gojs.Margin(0, 14, 0, 2), // leave room for Button
          font: 'bold 16px sans-serif',
        },
        new gojs.Binding('text', 'key')
      ),
      $(
        gojs.Panel,
        'Vertical',
        {
          name: 'LIST',
          row: 1,
          padding: 0, //表名到下边框的距离
          alignment: gojs.Spot.TopLeft,
          defaultAlignment: gojs.Spot.Left,
          stretch: gojs.GraphObject.Horizontal,
          //itemTemplate: itemTempl
        },
        new gojs.Binding('itemArray', 'items')
      )
    ) // end Table Panel
  ) // end Node
  myDiagram.value.linkTemplate = $(
    gojs.Link, // the whole link panel
    {
      selectionAdorned: true,
      layerName: 'Foreground',
      reshapable: true,
      routing: gojs.Link.AvoidsNodes,
      corner: 5,
      curve: gojs.Link.JumpOver,
      toEndSegmentLength: 100,
    },
    $(
      gojs.Shape, // the link shape
      { stroke: '#303B45', strokeWidth: 2.5 }
    ),
    $(
      gojs.TextBlock, // the "from" label
      {
        textAlign: 'center',
        font: 'bold 14px sans-serif',
        stroke: '#1967B3',
        segmentIndex: 0,
        segmentOffset: new gojs.Point(NaN, NaN),
        segmentOrientation: gojs.Link.OrientUpright,
      },
      new gojs.Binding('text', 'text')
    ),
    $(
      gojs.TextBlock, // the "to" label
      {
        textAlign: 'center',
        font: 'bold 14px sans-serif',
        stroke: '#1967B3',
        segmentIndex: -1,
        segmentOffset: new gojs.Point(NaN, NaN),
        segmentOrientation: gojs.Link.OrientUpright,
      },
      new gojs.Binding('text', 'toText')
    )
  )
  myDiagram.value.model = $(gojs.GraphLinksModel, {
    nodeDataArray: tabViewList.value,
    linkDataArray: tabRelView.value,
  })
}

const wrapperNode = (obj) => {
  let mainItems = []
  if (obj.attributesVOList && obj.attributesVOList.length > 0) {
    mainItems = obj.attributesVOList.map((val) => {
      return {
        name: val.code + ' ' + val.name,
        isKey: val.code === 'id',
        figure: '',
        color: '#1c446f',
      }
    })
  }
  tabViewList.value.push({
    key: obj.code + ' ' + obj.name,
    items: mainItems,
  })
  if (obj.linkBuss) {
    obj.linkBuss.forEach((val) => {
      var linkItems = []
      if (val.attributesVOList && val.attributesVOList.length > 0) {
        linkItems = val.attributesVOList.map((vo) => {
          return {
            name: vo.code + ' ' + vo.name,
            isKey: vo.code === 'id',
            figure: '',
            color: '#1c446f',
          }
        })
      }
      tabViewList.value.push({
        key: val.code + ' ' + val.name,
        items: linkItems,
      })
      tabRelView.value.push({
        from: obj.code + ' ' + obj.name,
        to: val.code + ' ' + val.name,
        text: '',
        toText: '',
      })
    })
  }
}
watch(
  () => visible.value,
  (newV) => {
    if (newV) {
      title.value = `${props.curRow.code + props.curRow.name}——关联的对象`
      let elementById = document.getElementById('entityRelation')
      if (elementById) {
        elementById.innerHTML = ''
      }
      myDiagram.value = {}
      tabRelView.value = []
      tabViewList.value = []
      getErAndRender()
    } else {
      myDiagram.value.isValid = false
      myDiagram.value.model = null
      myDiagram.value.toolManager = null
      myDiagram.value.diagramDiv = null
      myDiagram.value = null
    }
  }
)
</script>

<style lang="scss" scoped></style>
